#include <stdio.h>
#include <string.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_uart.h"
#include "iot_errno.h"

#define TASK_STACK_SIZE         1024*4                //任务栈大小
#define TASK_PRIO               20 
#define IOT_UART_IDX            1
#define BUFF_SIZE               100

static const unsigned char *data = "message from esp32";

void IotUartTask(void)
{
    int32_t ret;

    uint8_t uart_buff[BUFF_SIZE] = {0};
    uint8_t *uart_buff_p = uart_buff;
    
    IotUartAttribute uart_attr = {
        .baudRate = 115200,
        .dataBits = 8,
        .stopBits =1,
        .parity = 0,
    };

    //初始化UART driver
    ret = IoTUartInit(IOT_UART_IDX,&uart_attr);
    if (ret != IOT_SUCCESS)
    {
        printf("Init Uart Falied Error No : %d\n",ret);
        return;
    }
    // ret = IoTUartSetFlowCtrl(IOT_UART_IDX, IOT_FLOW_CTRL_NONE);
    printf("Uart Test Start!!!\n");
    ret = IoTUartWrite(IOT_UART_IDX,(unsigned char*)data,strlen(data));
    while (1){
        ret = IoTUartRead(IOT_UART_IDX,uart_buff_p,BUFF_SIZE);
        if (ret < 0) {
            printf("UartRead: read data failed, ret %d\n", ret);
        }else if(ret > 0){
            printf("read : %s\r\n",uart_buff_p);
            uart_buff_p[ret] = '\0';
            ret = IoTUartWrite(IOT_UART_IDX,(uint8_t *)uart_buff_p,strlen(uart_buff_p));
        }
        memset(uart_buff_p, 0, BUFF_SIZE);
        osDelay(1000);
    }
    ret = IoTUartDeinit(IOT_UART_IDX);
    if(ret == IOT_SUCCESS){
        printf("uart deinit success\r\n");
    }else{
        printf("uart deinit fail\r\n");
    }
    osThreadExit();
}

void IotUartDemo(void)
{
    osThreadAttr_t attr;

    attr.name = "Iot_UART_TASK_NAME";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = TASK_STACK_SIZE;
    attr.priority = TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)IotUartTask, NULL, &attr) == NULL) {
        printf("Failed to create thread!\n");
    }
}

APP_FEATURE_INIT(IotUartDemo);